package com.yt.system.service.impl;

import com.yt.system.dao.*;
import com.yt.system.domain.*;
import com.yt.system.service.ActiveService;
import com.yt.system.service.GroupAccountService;
import com.yt.system.service.GroupHistoryService;
import com.yt.system.service.HistoryService;
import com.yt.system.utils.PageHelperUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.validation.constraints.Pattern;
import java.net.DatagramPacket;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Clqv
 * @create 2019--09--18 16:00
 */
@Service
public class ActiveServiceImpl implements ActiveService {

    @Autowired
    ActivityMapper activityMapper;

    @Autowired
    AccountActivityMapper accountActivityMapper;

    @Autowired
    ActivitytypeMapper activitytypeMapper;

    @Autowired
    GroupMessageMapper groupMessageMapper;

    @Autowired
    GroupMapper groupMapper;

    @Autowired
    AccountMapper accountMapper;

    @Autowired
    VoteMapper voteMapper;

    @Autowired
    AccountVoteMapper accountVoteMapper;

    @Autowired
    HistoryMapper historyMapper;

    @Autowired
    HistoryService historyService;

    @Autowired
    GroupHistoryService groupHistoryService;

    @Autowired
    GroupAccountService groupAccountService;

    @Autowired
    GroupHistoryMapper groupHistoryMapper;

    /**
     * 根据活动id查询某个活动
     * @param actid
     * @return
     * 某个活动记录
     */
    @Override
    public Activity getActiveBykey(Integer actid) {
        return activityMapper.selectByPrimaryKey(actid);
    }

    /**
     * 个人参加活动的业务逻辑方法
     * 先判断时间是否符合报名时间
     * 再判断是否超过活动限制人数，如超过限制人数就不插入参加记录
     * 如果没有超过限制人数，正常参加活动
     * 再判断用户是否已参加过此活动，参加过不能再参加
     * @param aid
     * @param actid
     * @return
     * 若程序出错导致无法插入信息而参加失败，返回0
     * 若报名成功返回1
     * 若不符合报名时间，返回2
     * 若参加小组数已到达上限，返回3
     * 若此小组已参加过此活动，返回4
     */
    @Override
    public Integer joinActiveForOne(Integer aid, Integer actid) {
        System.out.println("个人参加活动");
        Activity activity = activityMapper.selectByPrimaryKey(actid);
        Integer flag = 0;
        Date systime = new Date();
        long time1 = (long) (activity.getActstarttime().getTime() - 30 * 60 * 1000);
        long time2 = systime.getTime();
        //判断是否为正确的报名时间,活动开始前半小时
        if (time1>time2) {
            //判断此活动的人数是越界
            if (activity.getActjoinednum()<activity.getActjoinpeople()){
                //判断用户是否参加过此活动
                if (accountActivityMapper.selectByAidAndActid(aid,actid)==null){
                    AccountActivity accountActivity = new AccountActivity();
                    accountActivity.setAid(aid);
                    accountActivity.setActid(actid);
                    accountActivity.setState("自愿参加");
                    accountActivity.setFlag(0);
                    accountActivityMapper.insertSelective(accountActivity);
                    activity.setActjoinednum(activity.getActjoinednum()+1);
                    activityMapper.updateByPrimaryKeySelective(activity);
                    flag = 1;
                }else {
                    flag = 4;
                }
            }else {
                 flag = 3;
            }
        }else{
            flag = 2;
        }
        return flag;
    }

    /**
     * 小组参加活动的业务逻辑方法
     * 先判断时间是否符合报名时间
     * 再判断是否超过活动限制人数，如超过限制人数就返回0，不插入参加记录
     * 如果没有超过限制人数，正常参加活动，返回1
     * 在判断用户是否已参加过此活动，参加过不能再参加
     * @param aid 账户id,
     * @param actid 活动id
     * @return
     * 若程序出错导致无法插入信息而参加失败，返回0
     * 若报名成功返回1
     * 若不符合报名时间，返回2
     * 若参加小组数已到达上限，返回3
     * 若此小组已参加过此活动，返回4
     */
    @Override
    public Integer joinActiveForGroup(Integer aid, Integer actid) {
        System.out.println("小组参加活动");
        Activity activity = activityMapper.selectByPrimaryKey(actid);
        Integer flag = 0;
        Date systime = new Date();
        long time1 = (long) (activity.getActstarttime().getTime() - 30 * 60 * 1000);
        long time2 = systime.getTime();
        AccountActivity accountActivity = new AccountActivity();
        GroupMessage groupMessage = groupMessageMapper.selectByaid(aid);
        //判断是否为小组的正确的报名时间,活动开始前半小时
        if (time1>time2) {
            //判断此活动的小组数是越界
            if (activity.getActjoinednum()<activity.getActjoinpeople()){
                //判断该小组是否参加过此活动
                if (accountActivityMapper.selectByAidAndActid(groupMessage.getGid(),actid)==null){
                    accountActivity.setAid(groupMessage.getGid());
                    accountActivity.setActid(actid);
                    accountActivity.setState("自愿参加");
                    accountActivity.setFlag(0);
                    accountActivityMapper.insertSelective(accountActivity);
                    activity.setActjoinednum(activity.getActjoinednum()+1);
                    activityMapper.updateByPrimaryKeySelective(activity);
                    flag = 1;
                }else {
                    flag = 4;
                }
            }else {
                flag = 3;
            }
        }else{
            flag = 2;
        }
        return flag;
    }

    /**
     * 用户退出活动的业务逻辑
     * @param aid 账户id
     * @param actid 活动id
     * @return
     * 返回1则为退出成功，返回2则为用户未参加此活动,返回3则为活动已经进行，否则就是退出失败
     */
    @Override
    public Integer takeoutActiveForOne(Integer aid, Integer actid) {
        AccountActivity accountActivity = accountActivityMapper.selectByAidAndActid(aid,actid);
        Activity activity = activityMapper.selectByPrimaryKey(actid);
        Integer flag = 0;
        Date systime = new Date();
        long time1 = activity.getActstarttime().getTime();
        long time2 = systime.getTime();
        if (time1>time2){
            if (accountActivityMapper.selectByAidAndActid(aid,actid)!=null){
                accountActivity.setFlag(1);
                flag = accountActivityMapper.updateByPrimaryKeySelective(accountActivity);
                if (flag>0){
                    activity.setActjoinednum(activity.getActjoinednum()-1);
                    activityMapper.updateByPrimaryKeySelective(activity);
                }
            }else {
                flag = 2;
            }
        }else {
            flag = 3;
        }
        return flag;
    }

    /**
     * 用户所在的小组退出活动的业务逻辑
     * @param aid 账户id
     * @param actid 活动id
     * @return
     * 返回1则为退出成功，返回2则为用户所在的小组未参加此活动,返回3则为活动已经进行，否则就是退出失败
     */
    @Override
    public Integer takeoutActiveForGroup(Integer aid, Integer actid) {
        GroupMessage groupMessage = groupMessageMapper.selectByaid(aid);
        AccountActivity accountActivity = accountActivityMapper.selectByAidAndActid(groupMessage.getGid(),actid);
        Activity activity = activityMapper.selectByPrimaryKey(actid);
        Integer flag = 0;
        Date systime = new Date();
        long time1 = activity.getActstarttime().getTime();
        long time2 = systime.getTime();
        if (time1>time2){
            if (accountActivityMapper.selectByAidAndActid(groupMessage.getGid(),actid)!=null){
                accountActivity.setFlag(1);
                flag = accountActivityMapper.updateByPrimaryKeySelective(accountActivity);
                if (flag>0){
                    activity.setActjoinednum(activity.getActjoinednum()-1);
                    activityMapper.updateByPrimaryKeySelective(activity);
                }
            }else {
                flag = 2;
            }
        }else {
            flag = 3;
        }
        return flag;
    }

    /**
     * 根据用户id查询用户参加活动的信息
     * @param aid
     * @return
     * 返回用户参加活动的信息
     */
    @Override
    public List<AccountActivity> getActiveByaid(Integer aid) {
        List<AccountActivity> accountActivities = new ArrayList<>();
        List<AccountActivity> accountActivitys = accountActivityMapper.selectByAid(aid);
        for (AccountActivity accountActivity : accountActivitys){
            System.out.println("accountActivity："+accountActivity);
            if (accountActivity.getActivity() != null){
                if (accountActivity.getActivity().getActivitytype().getAcflag()==1){
                    accountActivities.add(accountActivity);
                }
            }
        }
        return accountActivities;
    }

    /**
     * 查询所有已发布且未结束的活动
     * @return
     * 返回所有已发布且未结束的活动信息
     */
    @Override
    public List<Activity> getActives() {
        Date systime = new Date();
        List<Activity> activities = activityMapper.selectAll(systime);
        return activities;
    }

    /**
     * 查询所有已发布且未开始的活动
     * @return
     * 返回所有未开始的活动信息
     */
    @Override
    public List<Activity> getActivesNoStart() {
        Date systime = new Date();
        List<Activity> activities = activityMapper.getActivesNoStart(systime);
        return activities;
    }

    /**
     * 查询所有已发布且未结束的活动
     * @return
     * 返回所有的活动信息
     */
    @Override
    public List<Activity> getActivesStarted() {
        Date systime = new Date();
        List<Activity> activities = activityMapper.getActivesStarted(systime);
        return activities;
    }

    /**
     * 查询所有已结束的活动
     * @return
     * 返回所有已结束的活动
     */
    @Override
    public List<Activity> getActivesforEnd(){
        Date systime = new Date();
        List<Activity> activities = activityMapper.selectEndActives(systime);
        return activities;
    }

    /**
     * 查询某个个人活动活动的具体信息以及参赛人员
     * @param actid
     * @return
     * 返回该个人活动所有参赛的具体信息，可从其中一条获取到该活动的具体信息
     */
    @Override
    public List<AccountActivity> getAccountActivitysByActid(Integer actid) {
        List<AccountActivity> accountActivities = accountActivityMapper.selectByActid(actid);
        return accountActivities;
    }

    /**
     * 查询某个小组活动活动的具体信息以及参赛人员
     * @param actid
     * @return
     * 返回该小组活动所有参赛的具体信息，可从其中一条获取到该活动的具体信息
     */
    @Override
    public List<AccountActivity> getAccountActivitysByActidForgroup(Integer actid) {
        List<AccountActivity> accountActivities = accountActivityMapper.selectByActidForGroup(actid);
        return accountActivities;
    }


    /**
     * 推迟活动时间的业务逻辑
     * @param actid 活动id
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return
     * 返回1则为推迟成功，返回2则为传入结束时间小于传入开始时间，3为传入开始时间小于原本开始时间，
     * 4为该活动已开始，不可推迟；0为推迟失败
     */
    @Override
    public Integer pushActiveTime(Integer actid, Date startTime,Date endTime) {
        Integer flag = 0;
            Activity activity = activityMapper.selectByPrimaryKey(actid);
            Date systime = new Date();
            long time1 = startTime.getTime();//传入的开始时间
            long time2 = systime.getTime();//系统时间
            long time3 = endTime.getTime();//传入的结束时间
            long oldstartime = activity.getActstarttime().getTime();//原本的开始时间
            long oldendtime = activity.getActendtime().getTime();
            //判断该活动是否已开始
            if (time2<oldstartime){
                //判断传入开始时间是否大于原来开始时间
                if (time1>oldstartime){
                    //判断结束时间是否大于开始时间
                        if (time3>time1){
                            activity.setActstarttime(startTime);
                            activity.setActendtime(endTime);
                            flag = activityMapper.updateByPrimaryKeySelective(activity);
                    }else {
                        flag = 2;
                    }
                }else {
                    flag = 3;
                }
            }else {
                flag = 4;
            }
        return flag;
    }

    /**
     * 发布活动
     * @param activity
     * @return
     * 返回1为发布成功，返回2为开始时间大于结束时间，返回3为系统时间大于开始时间，0为系统错误，发布失败
     */
    @Override
    public Integer publishActive(Activity activity) {
        activity.setActjoinednum(0);
        Date date = new Date();
        long systime = date.getTime();
        long starttime = activity.getActstarttime().getTime();
        long endtime = activity.getActendtime().getTime();
        Integer flag = 0;
        //判断开始时间是否小于结束时间
        if (starttime<endtime){
            //判断时间开始时间是否大于系统时间
            if (starttime>systime){
                activity.setActjoinednum(0);
                activity.setActupdtime(date);
                flag = activityMapper.insertSelective(activity);
            }else {
                flag = 3;
            }
        }else {
            flag = 2;
        }
        return flag;
    }

    /**
     * 更新活动信息
     * @param activity
     * @return
     * 返回1为更新成功，返回2为开始时间大于结束时间，返回3为系统时间大于开始时间，0为系统错误，更新失败
     */
    @Override
    public Integer updateActive(Activity activity) {
        Date date = new Date();
        long systime = date.getTime();
        long starttime = activity.getActstarttime().getTime();
        long endtime = activity.getActendtime().getTime();
        Integer flag = 0;
        //判断开始时间是否小于结束时间
        if (starttime<endtime){
            //判断时间开始时间是否大于系统时间
            if (starttime>systime){
                activity.setActupdtime(date);
                flag = activityMapper.updateByPrimaryKeySelective(activity);
                System.out.println("flag:"+flag);
            }else {
                flag = 3;
            }
        }else {
            flag = 2;
        }
        return flag;
    }

    /**
     * 删除活动
     * @param actid
     * @return
     * 返回1为删除成功，返回2为活动已开始但未结束，不能删除,返回0为系统错误，删除失败
     */
    @Override
    public Integer deleteActive(Integer actid) {
        Activity activity = activityMapper.selectByPrimaryKey(actid);
        Date date = new Date();
        long systime = date.getTime();
        long starttime = activity.getActstarttime().getTime();
        long endtime = activity.getActendtime().getTime();
        Integer flag = 0;
        //判断该活动是否已经开始,且未结束
        if (systime<starttime||systime>endtime){
            flag = activityMapper.deleteByPrimaryKey(actid);
        }else {
            flag = 2;
        }
        return flag;
    }

    /**
     * 开启/关闭系统自动强制参加
     * @param actid 活动id
     * @param flag 标识，0为开启，1为关闭
     * @return
     * 返回1为关闭成功；2为关闭失败，活动开始前30分钟内不能再关闭；3为开启成功；4为开启失败，在活动开始前15分钟不能开启此功能
     */
    @Override
    public Integer updateForceJoin(Integer actid, Integer flag) {
        Activity activity = activityMapper.selectByPrimaryKey(actid);
        Date date = new Date();
        long systime = date.getTime();
        long starttime = activity.getActstarttime().getTime();
        long time30 = (long) (activity.getActstarttime().getTime() - 30 * 60 * 1000);
        long time15 = (long) (activity.getActstarttime().getTime() - 15 * 60 * 1000);
        Integer flag1 = 0;
        activity.setFlag(flag);
        //判断该活动报名是否处于未结束状态
        if(flag==1){
            if (systime<time30){
                flag1 = activityMapper.updateByPrimaryKeySelective(activity);
            }else {
                flag1 = 2;
            }
        }else {
            if (systime<time15){
                activityMapper.updateByPrimaryKeySelective(activity);
                flag1 = 3;
            }else {
                flag1 = 4;
            }
        }
        return flag1;
    }

    /**
     * 根据活动名字模糊查询
     * @param keywords
     * @return
     * 模糊查询后的结果
     */
    @Override
    public List<Activity> searchActiveByName(String keywords) {
        List<Activity> activities = new ArrayList<>();
        List<Integer> ids = new ArrayList<>();
        if (keywords != null){
            List<Activity> activities1 = activityMapper.searchActiveByName(keywords);
            if (!activities1.isEmpty()){
                for (Activity activity : activities1){
                    ids.add(activity.getActid());
                }
            }
            List<Activity> activities2 = activityMapper.searchActiveByContent(keywords);
            if (!activities2.isEmpty()){
                for (Activity activity : activities2){
                    System.out.println(activity);
                    ids.add(activity.getActid());
                }
            }
            List<Activity> activities3 = activityMapper.searchActiveByAdress(keywords);
            if (!activities3.isEmpty()){
                for (Activity activity : activities3){
                    ids.add(activity.getActid());
                }
            }
            List<Integer> collect = ids.stream().distinct().collect(Collectors.toList());
            if (!ids.isEmpty()){
                for (Integer id : collect){
                    activities.add(activityMapper.selectByPrimaryKey(id));
                }
            }
        }
        return activities;
    }


//----------------------------------------------------------------------------------------------活动类型业务逻辑------------------------------------------------------------------------------
    /**
     * 查询所有的活动类型
     * @return
     * 返回所有的活动类型信息
     */
    @Override
    public List<Activitytype> getActiveTypes() {
        List<Activitytype> activitytypes = activitytypeMapper.getActiveTypes();
        return activitytypes;
    }

    /**
     * 添加新的活动类型
     * @param activitytype
     * @return
     * 返回1为添加成功，返回0为系统错误，添加失败
     */
    @Override
    public Integer addActiveType(Activitytype activitytype) {
        Integer flag = activitytypeMapper.insertSelective(activitytype);
        return flag;
    }

    /**
     * 更新活动类型
     * @param activitytype
     * @return
     * 返回1为更新成功，返回0为系统错误，更新失败
     */
    @Override
    public Integer updateActiveType(Activitytype activitytype) {
        return activitytypeMapper.updateByPrimaryKeySelective(activitytype);
    }

    /**
     * 删除活动类型
     * @param acid
     * @return
     * 返回1为删除成功，返回2为有该活动类型的活动未结束，不能删除，返回0为系统错误，删除失败
     */
    @Override
    public Integer deleteActiveType(Integer acid) {
        List<Activity> activities = activityMapper.selectByAcid(acid);
        Date date = new Date();
        Integer flag = 2;
        for (Activity activity : activities){
            long systime = date.getTime();
            long endtime = activity.getActendtime().getTime();
            if (systime>endtime){
               flag = activitytypeMapper.deleteByPrimaryKey(acid);
            }
        }
        return flag;
    }

//----------------------------------------------------------------------------------------------活动投票业务逻辑------------------------------------------------------------------------------

    /**
     * 开启投票
     * @param actid
     * @return
     * 返回1是开启成功，返回2是不符合开启时间要求，必须在活动开始半小时后才能开启投票，返回3为此活动已开启投票，不能再开
     */
    @Override
    public Integer startVote(Integer actid) {
        Integer flag = 0;
            List<AccountActivity> accountActivities = accountActivityMapper.selectByActid(actid);
            Activity activity = activityMapper.selectByPrimaryKey(actid);
            Date date = new Date();
            long systime = date.getTime();
            long starttime = (long) (activity.getActstarttime().getTime() + 30 * 60 * 1000);
            long endtime = activity.getActendtime().getTime();
            if (systime>starttime&&systime<endtime){
                if (activity.getVflag()==0){
                    for (AccountActivity accountActivity : accountActivities){
                        if (voteMapper.getVoteByaidAndactid(accountActivity.getAid(),accountActivity.getActid())==null){
                            Vote vote = new Vote();
                            vote.setActid(actid);
                            vote.setAid(accountActivity.getAid());
                            vote.setVnum(0);
                            flag = voteMapper.insertSelective(vote);
                        }else {
                            flag = 3;
                        }
                        if (flag>0){
                            activity.setVflag(1);
                            flag = activityMapper.updateByPrimaryKeySelective(activity);
                        }
                    }
                }else {
                    flag = 3;
                }
            }else {
                flag = 2;
            }
        return flag;
    }

    /**
     * 获得该活动所有的投票记录
     * @param actid 活动id
     * @return
     * 返回该活动所有的投票记录
     */
    @Override
    public List<Vote> getVotes(Integer actid) {
        Activity activity = activityMapper.selectByPrimaryKey(actid);
        List<Vote> votes = null;
        if (activity.getVflag()==1){
            if (activity.getActivitytype().getAcflag()==1){
                votes = voteMapper.getVotes(actid);
            }else if (activity.getActivitytype().getAcflag()==2){
                votes = voteMapper.getVotesForGroup(actid);
            }
        }
        return votes;
    }

    /**
     * 获得该活动前十条的投票记录
     * @param actid 活动id
     * @return
     * 返回该活动所有前十条的投票记录
     */
    @Override
    public List<Vote> getVotesBefore(Integer actid) {
        Activity activity = activityMapper.selectByPrimaryKey(actid);
        List<Vote> votes = null;
        if (activity.getActivitytype().getAcflag()==1){
            votes = voteMapper.getVotesBefore(actid);
        }else if (activity.getActivitytype().getAcflag()==2){
            votes = voteMapper.getVotesBeforeForGroup(actid);
        }
        return votes;
    }

    /**
     * 投票
     * @param actid 活动id
     * @param aid 投票者id
     * @param vid 所投记录id
     * @return
     * 返回1为投票成功，返回2为此用户已投过票，返回3则为该活动投票功能已结束
     */
    @Override
    public Integer Voted(Integer actid, Integer aid, Integer vid) {
        Integer flag = 0;
        Activity activity = activityMapper.selectByPrimaryKey(actid);
        Date date = new Date();
        long systime = date.getTime();
        long endtime = activity.getActendtime().getTime();
        if (systime<endtime){
            if(accountVoteMapper.selectByActidAndAid(aid,actid)==null){
                if (activityMapper.selectByPrimaryKey(actid).getVflag()==1){
                    AccountVote accountVote = new AccountVote();
                    accountVote.setAid(aid);
                    accountVote.setVid(vid);
                    accountVote.setActid(actid);
                    Integer flag1 = accountVoteMapper.insertSelective(accountVote);
                    if (flag1>0){
                        Vote vote = voteMapper.selectByPrimaryKey(vid);
                        vote.setVnum(vote.getVnum()+1);
                        flag = voteMapper.updateByPrimaryKey(vote);
                    }
                }else {
                    flag = 3;
                }
            }else {
                flag = 2;
            }
        }else {
            flag = 3;
        }
        return flag;
    }


    /**
     * 手动关闭投票
     * @param actid 活动id
     * @return
     * 返回1为关闭投票成功，系统已自动结算结果；返回2为该活动没有开启投票；
     */
    @Override
    public Integer finishVote(Integer actid) {
        Activity activity = activityMapper.selectByPrimaryKey(actid);
        Integer flag = 0;
        //判断该活动是否已开启投票
        if (activity.getVflag()==1){
            //根据活动类型判断是个人赛还是小组赛
            if (activity.getActivitytype().getAcflag()==1){
                List<Vote> votes = voteMapper.getVotes(actid);
                Integer i = 1;
                Double j = 3.0;
                Double k =0.0;
                //获得个人赛排名并添加积分记录
                for (Vote vote : votes){
                    vote.setRanking(i);
                    if(j>0){
                        vote.setIntegral(j+activity.getActivitytype().getScore());
                    }else{
                        vote.setIntegral(k+activity.getActivitytype().getScore());
                    }
                    if(i<4){
                        vote.setNotes("在"+activity.getActname()+"活动荣获得第"+i+"名，积分+"+(j+activity.getActivitytype().getScore())+"分");
                    }else{
                        vote.setNotes("参于"+activity.getActname()+"活动获得第"+i+"名，参与活动基础分+"+activity.getActivitytype().getScore()+"分");
                    }
                    voteMapper.updateByPrimaryKey(vote);
                    j--;
                    i++;
                    //将根据排名获得的积分插入到积分历史表当中去
                    History history = new History();
                    history.setAid(vote.getAid());
                    history.setOperatesorce(vote.getIntegral());
                    history.setReason(vote.getNotes());
                    System.out.println(vote.getIntegral());
                    //获取用户当前的积分
                    Double score = historyService.selectScoreByAid(history.getAid());
                    //获取加减分字符串
                    Double operatescore = history.getOperatesorce();
                    score+=operatescore;
                    history.setTotalchange(score);
                    historyService.insert(history);
                    Account account = new Account();
                    account.setAid(history.getAid());
                    account.setAintegral(score);
                    flag = historyService.updateByPrimaryKeySelective(account);
                    if (flag>0){
                        activity.setVflag(0);
                        activityMapper.updateByPrimaryKeySelective(activity);
                    }
                }
            //活动类型为小组活动
            }else if(activity.getActivitytype().getAcflag()==2){
                List<Vote> votes = voteMapper.getVotes(actid);
                Integer i = 1;
                Double j = 3.0;
                Double k =0.0;
                //获得活动赛排名并添加积分记录
                for (Vote vote : votes){
                    vote.setRanking(i);
                    if(j>0){
                        vote.setIntegral(j+activity.getActivitytype().getScore());
                    }else{
                        vote.setIntegral(k+activity.getActivitytype().getScore());
                    }
                    if(i<4){
                        vote.setNotes("在小组活动"+activity.getActname()+"中本小组荣获得第"+i+"名，积分+"+(j+activity.getActivitytype().getScore())+"分");
                    }else{
                        vote.setNotes("参于小组活动"+activity.getActname()+"获得第"+i+"名，参与活动基础分+"+activity.getActivitytype().getScore()+"分");
                    }
                    voteMapper.updateByPrimaryKey(vote);
                    j--;
                    i++;
                    //将根据排名获得的积分插入到积分历史表当中去
                    GroupHistory groupHistory = new GroupHistory();
                    groupHistory.setGid(vote.getAid());
                    groupHistory.setOperatesorce(vote.getIntegral());
                    groupHistory.setReason(vote.getNotes());
                    System.out.println(vote.getIntegral());
                    //获取用户当前的积分
                    Double score = historyService.selectScoreByAid(groupHistory.getGid());
                    Double operatescore = groupHistory.getOperatesorce();
                    score+=operatescore;
                    groupHistory.setTotalchange(score);
                    groupHistoryService.insertGroupHistory(groupHistory);
                    if (flag>0){
                        activity.setVflag(0);
                        activityMapper.updateByPrimaryKeySelective(activity);
                    }
                }
            }
        }else {
            flag = 2;
        }
        return flag;
    }



//----------------------------------------------------------------------------------------------系统自动扫描业务逻辑------------------------------------------------------------------------------
    /**
     * 系统扫描自动强制参加
     *当举办半小时前参加人数不达人数上限将随机抽取小组或用户强制参与该活动，可由管理员选择是否开启此功能
     */
    // 表示每15分钟执行一次
    @Async
    @Scheduled(cron = "0 0/15 * * * ?")
    public void forceJoin() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date sysdate = new Date();
        String viewtime = sdf.format(sysdate);
        System.out.println("在"+viewtime+"时强制参加扫描......");
        long systime = sysdate.getTime();
        List<Activity> activities = activityMapper.getActivesNoStart(sysdate);
        int i = 0;
        for (Activity activity:activities){
            System.out.println("i："+i+"活动："+activity.getActname());
            i++;
            long starttime = (long) (activity.getActstarttime().getTime() - 30 * 60 * 1000);
            long starttime1 = activity.getActstarttime().getTime();
            Activitytype activitytype = activitytypeMapper.selectByPrimaryKey(activity.getAcid());
            //先判断是该活动否开启了强制参加
            if (activity.getFlag()==0){
                System.out.println("该活动已开启强制参加");
                //再判断该活动的人数是否到达上限
                if (activity.getActjoinpeople()>activity.getActjoinednum()){
                    System.out.println("该活动没有达到人数上限");
                    //再判断系统时间是否处于该活动开始前半个小时内
                    if (systime>starttime&&systime<starttime1){
                        System.out.println("该活动在强制参加的时间内");
                        //根据活动类型判断强制用户还是小组
                        if (activitytype.getAcflag()==1){
                            System.out.println("随机抽取用户参与该活动："+activity.getActname()+"("+activity.getActivitytype().getAcflag()+")");
                            List<Account> accounts = accountMapper.getAllAccount();
                            Collections.shuffle(accounts);
                            //循环账户的随机列表
                            for (Account account:accounts){
                                //随机用户强制参加该活动，知道人数到达上限为止
                                if (activity.getActjoinpeople()>activity.getActjoinednum()){
                                    //判断用户没有参与过此活动
                                    if (accountActivityMapper.selectByAidAndActid(account.getAid(),activity.getActid())==null){
                                        AccountActivity accountActivity = new AccountActivity();
                                        accountActivity.setAid(account.getAid());
                                        accountActivity.setActid(activity.getActid());
                                        accountActivity.setState("强制参加");
                                        accountActivity.setFlag(0);
                                        int flag = accountActivityMapper.insertSelective(accountActivity);
                                        if (flag>0){
                                            activity.setActjoinednum(activity.getActjoinednum()+1);
                                            activityMapper.updateByPrimaryKeySelective(activity);
                                        }
                                    }
                                }
                            }
                        }else if(activitytype.getAcflag()==2){
                            System.out.println("随机抽取小组参与该活动："+activity.getActname());
                            List<GroupTable> groupTables = groupMapper.getGroups();
                            Collections.shuffle(groupTables);
                            //循环小组的随机列表
                            for (GroupTable groupTable : groupTables){
                                System.out.println("随机小组列表："+groupTable.getGname());
                                //随机小组强制参加该活动，直到人数到达上限为止
                                if (activity.getActjoinpeople()>activity.getActjoinednum()){
                                    System.out.println("人数没有达到上限");
                                        //判断小组没有参与过此活动
                                        if (accountActivityMapper.selectByAidAndActid(groupTable.getGid(),activity.getActid())==null){
                                            System.out.println(groupTable.getGname()+"没有参加过此活动");
                                            System.out.println("随机抽取该小组参加此活动："+groupTable.getGname()+activity.getActname()+"("+activity.getActivitytype().getAcflag()+")");
                                            AccountActivity accountActivity = new AccountActivity();
                                            accountActivity.setAid(groupTable.getGid());
                                            accountActivity.setActid(activity.getActid());
                                            accountActivity.setState("强制参加");
                                            accountActivity.setFlag(0);
                                            int flag = accountActivityMapper.insertSelective(accountActivity);
                                            if (flag>0){
                                                activity.setActjoinednum(activity.getActjoinednum()+1);
                                                activityMapper.updateByPrimaryKeySelective(activity);
                                            }
                                        }
                                }
                            }
                        }
                    }
                }
            }
        }
    }



    /**
     * 系统自动结束投票并结算投票结果得出排名和为用户添加相应的积分
     *
     * 每30分钟扫描一次
     */
    @Async
    @Scheduled(cron = "0 0/20 * * * ?")
    public void finishVoteOnsystem() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String viewtime = sdf.format(date);
        System.out.println("在"+viewtime+"时自动结束投票结算扫描......");
        List<Activity> activities = activityMapper.selectEndActives(date);
        Integer flag = 0;
        for (Activity activity : activities){
            long systime = date.getTime();
            long endtime = activity.getActendtime().getTime();
            //判断该活动是否已经结束
            if (systime>endtime){
                //判断该活动是否已开启投票
                if (activity.getVflag()==1){
                    //根据活动类型判断是个人赛还是小组赛
                    if (activity.getActivitytype().getAcflag()==1){
                        List<Vote> votes = voteMapper.getVotes(activity.getActid());
                        Integer i = 1;
                        Double j = 3.0;
                        Double k = 0.0;
                        //获得个人赛排名并添加积分记录
                        for (Vote vote : votes){
                            vote.setRanking(i);
                            if(j>0){
                                vote.setIntegral(j+activity.getActivitytype().getScore());
                            }else{
                                vote.setIntegral(k+activity.getActivitytype().getScore());
                            }
                            if(i<4){
                                vote.setNotes("在"+activity.getActname()+"活动荣获得第"+i+"名，积分+"+(j+activity.getActivitytype().getScore())+"分");
                            }else{
                                vote.setNotes("参于"+activity.getActname()+"活动获得基础分+"+activity.getActivitytype().getScore()+"分");
                            }
                            voteMapper.updateByPrimaryKey(vote);
                            j--;
                            i++;
                            //将根据排名获得的积分插入到积分历史表当中去
                            History history = new History();
                            history.setAid(vote.getAid());
                            history.setOperatesorce(vote.getIntegral());
                            history.setReason(vote.getNotes());
                            //获取用户当前的积分
                            Double score = historyService.selectScoreByAid(history.getAid());
                            Double operatescore = history.getOperatesorce();
                            score+=operatescore;
                            history.setTotalchange(score);
                            historyService.insert(history);
                            Account account = new Account();
                            account.setAid(history.getAid());
                            account.setAintegral(score);
                            flag = historyService.updateByPrimaryKeySelective(account);
                            if (flag>0){
                                activity.setVflag(0);
                                activityMapper.updateByPrimaryKeySelective(activity);
                            }
                        }
                    }else if(activity.getActivitytype().getAcflag()==2){
                        List<Vote> votes = voteMapper.getVotes(activity.getActid());
                        Integer i = 1;
                        Double j = 3.0;
                        Double k =0.0;
                        //获得活动赛排名并添加积分记录
                        for (Vote vote : votes){
                            vote.setRanking(i);
                            if(j>0){
                                vote.setIntegral(j+activity.getActivitytype().getScore());
                            }else{
                                vote.setIntegral(k+activity.getActivitytype().getScore());
                            }
                            if(i<4){
                                vote.setNotes("在小组活动"+activity.getActname()+"中本小组荣获得第"+i+"名，积分+"+(j+activity.getActivitytype().getScore())+"分");
                            }else{
                                vote.setNotes("参于小组活动"+activity.getActname()+"获得第"+i+"名，参与活动基础分+"+activity.getActivitytype().getScore()+"分");
                            }
                            voteMapper.updateByPrimaryKey(vote);
                            j--;
                            i++;
                            //将根据排名获得的积分插入到积分历史表当中去
                            GroupHistory groupHistory = new GroupHistory();
                            groupHistory.setGid(vote.getAid());
                            groupHistory.setOperatesorce(vote.getIntegral());
                            groupHistory.setReason(vote.getNotes());
                            System.out.println(vote.getIntegral());
                            //获取用户当前的积分
                            Double score = historyService.selectScoreByAid(groupHistory.getGid());
                            Double operatescore = groupHistory.getOperatesorce();
                            score+=operatescore;
                            groupHistory.setTotalchange(score);
                            flag = groupHistoryService.insertGroupHistory(groupHistory);
                            if (flag>0){
                                activity.setVflag(0);
                                activityMapper.updateByPrimaryKeySelective(activity);
                            }
                        }
                    }
                }else {
                    flag = 2;
                }
            }else {
                flag = 3;
            }
            System.out.println("flag:"+flag);
        }
    }

}
